﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

class SearchingStringInFiles
{
    static void Main(string[] args)
    {
        string stringToBeSearched = "student";
        string folder = @"C:\";
        string outputFile = "result.txt";
        File.Delete(outputFile);
        SearchStringInDirectories(folder, stringToBeSearched, outputFile);
    }

    static void SearchStringInDirectories(string folder, string stringToBeSearched, string outputFile)
    {
        try
        {
            DirectoryInfo folderInfo = new DirectoryInfo(folder);
            FileInfo[] files = folderInfo.GetFiles();
            DirectoryInfo[] directories = folderInfo.GetDirectories();

            foreach (FileInfo file in files)
            {

                if (file.Name.EndsWith(".txt"))
                {
                    SearchStringInFiles(file.FullName, stringToBeSearched, outputFile);
                }
            }

            foreach (DirectoryInfo directory in directories)
            {
                SearchStringInDirectories(directory.FullName, stringToBeSearched, outputFile);
            }
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine("Could not access {0} file.", (new DirectoryInfo(folder)).FullName);
        }
    }

    static void SearchStringInFiles(string file, string stringToBeSearched, string outputFile)
    {
       // Console.WriteLine("file :" + file);
        try
        {
            using (StreamReader reader = File.OpenText(file))
            {
                using (StreamWriter writer = new StreamWriter(outputFile, true))
                {
                    int lineNumber = 0;
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        lineNumber++;
                        if (line.IndexOf(stringToBeSearched) > -1)
                        {
                            writer.WriteLine((new FileInfo(file)).FullName + ": ");
                            writer.WriteLine("{0:0000}: {1}", lineNumber, line);
                            writer.WriteLine();
                            break;
                        }
                    }
                }
            }
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine("Could not access {0} file.", (new FileInfo(file)).FullName);
        }
        catch (IOException e)
        {
            Console.WriteLine("File "+ (new FileInfo(file)).FullName + "is being used by another user.");
        }
    }
}

